/*
 * @Author: g05047
 * @Date: 2023-04-20 17:24:34
 * @LastEditors: g05047
 * @LastEditTime: 2023-08-11 15:04:27
 * @Description: file content
 */
import axios from "axios";
import { Message, Loading } from "element-ui";
import { timestamp } from "@/utils/timestamp"
import { GetSSAToken } from "@/utils/auth";


// create an axios instance
const service = axios.create({
  baseURL: "", // api 的 base_url
  timeout: 120 * 1000 // request timeout
});
let loadingInstance = "";
// request interceptor
service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: '拼命加载中……',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // Do something before request is sent
    if (!(sessionStorage.getItem('SSA_TOKEN') && sessionStorage.getItem('SSA_USERID'))) {
      new Promise((resolve, reject) => {
        GetSSAToken()
          .then((response) => {
            if (response.data.code == "200") {
              let token = response.data.data;
              sessionStorage.setItem('SSA_TOKEN', token)
            }
            resolve();
          }).catch((error) => {
            console.log(error);
          });
      })
    }

    config.headers.timestamp = timestamp();
    config.headers.id = sessionStorage.getItem('SSA_USERID')
    config.headers.code = sessionStorage.getItem('SSA_TOKEN')

    return config;
  },
  error => {
    loadingInstance.close();
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code == null) {
        loadingInstance.close();
        return response.data;
      }
      else if (res.code === 408) {
        //重新登录
        new Promise((resolve, reject) => {
          GetSSAToken()
            .then((response) => {
              if (response.data.code == "200") {
                let token = response.data.data;
                sessionStorage.setItem('SSA_TOKEN', token)

              }
              resolve();
            }).catch((error) => {
              console.log(error);
            });
        })
        // Message({
        //   message: '登录信息过期，请刷新页面',
        //   type: "error",
        //   duration: 5 * 1000
        // });
      } else {
        console.log("res.msg:", res.msg)
        /*消息提醒*/
        Message({
          message: res.msg,
          type: "error",
          duration: 5 * 1000
        });
      }
      loadingInstance.close();
      return Promise.reject("error");
    } else {
      loadingInstance.close();
      return response.data;
    }
  },
  error => {
    loadingInstance.close();
    console.log("err" + error); // for debug
    /*消息提醒*/
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error);
  }
);

export default service;
